#include <iostream>
#include <cstring>
#include <arpa/inet.h> // 对于Windows系统使用 #include <winsock2.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>

// 检查系统是否是大端字节序
bool is_big_endian() {
    uint16_t num = 0x1;
    return *(reinterpret_cast<char*>(&num)) == 0;
}

// 字节序转换函数
uint16_t swap_endian(uint16_t val) {
    return (val << 8) | (val >> 8);
}

uint32_t swap_endian(uint32_t val) {
    return ((val << 24) & 0xFF000000) |
           ((val << 8)  & 0x00FF0000) |
           ((val >> 8)  & 0x0000FF00) |
           ((val >> 24) & 0x000000FF);
}

void server() {
    int server_fd, new_socket;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    uint32_t data;

    // 创建服务器套接字
    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 绑定服务器地址
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(8080); // 端口号转换为网络字节序

    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 监听连接
    if (listen(server_fd, 3) < 0) {
        perror("listen");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 接受客户端连接
    new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen);
    if (new_socket < 0) {
        perror("accept");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 接收数据
    read(new_socket, &data, sizeof(data));
    data = ntohl(data); // 转换为主机字节序

    std::cout << "接收到的数据（主机字节序）: 0x" << std::hex << data << std::endl;

    close(new_socket);
    close(server_fd);
}

void client() {
    struct sockaddr_in address;
    int sock = 0;
    uint32_t data = 0x12345678;
    struct sockaddr_in serv_addr;

    // 创建客户端套接字
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        std::cerr << "Socket creation error" << std::endl;
        return;
    }

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(8080); // 端口号转换为网络字节序

    // 连接到服务器
    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        std::cerr << "Connection Failed" << std::endl;
        close(sock);
        return;
    }

    data = htonl(data); // 转换为网络字节序
    send(sock, &data, sizeof(data), 0);
    std::cout << "数据已发送" << std::endl;

    close(sock);
}

int main() {
    pid_t pid = fork();

    if (pid == 0) {
        sleep(1); // 等待服务器启动
        client();
    } else if (pid > 0) {
        server();
    } else {
        std::cerr << "Fork failed" << std::endl;
        return 1;
    }

    return 0;
}